<script setup lang="ts">
import { ref, onMounted } from "vue";
import ReCol from "@/components/ReCol";
import { formRules } from "./utils/rule";
import { FormProps } from "./utils/types";
import { handleTree } from "@/utils/tree";
import { getMenuList } from "@/api/system/menu";

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    id: null,
    bizType: 1,
    name: "",
    roleCode: "",
    menuIdList: []
  })
});

const ruleFormRef = ref();
const newFormInline = ref(props.formInline);

const treeRef = ref();
const treeLoading = ref(true);
const treeData = ref([]);
const defaultProps = {
  children: "children",
  label: "menuName"
};

function getRef() {
  return ruleFormRef.value;
}

function getTreeData() {
  newFormInline.value.menuIdList = treeRef.value
    .getCheckedKeys()
    .concat(treeRef.value.getHalfCheckedKeys());
}

/** 加载菜单tree */
const loadTree = async () => {
  treeLoading.value = true;
  // 获取菜单 类型 1平台端菜单 2平台端按钮 3店长端菜单 4店长端按钮
  let params = {
    menuTypeList: newFormInline.value.bizType == 1 ? [1, 2] : [3, 4],
    pageNum: 1,
    pageSize: 200
  };
  const { data } = await getMenuList(params);
  treeData.value = handleTree(data.records || []);
  // 默认选择第一个
  treeLoading.value = false;
};

onMounted(() => {
  loadTree();
  treeRef.value &&
    treeRef.value.setCheckedKeys(newFormInline.value.menuIdList || []);
});

defineExpose({ getRef, getTreeData });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="82px"
  >
    <el-row justify="center">
      <re-col :value="16">
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="newFormInline.name"
            clearable
            placeholder="请输入角色名称"
          />
        </el-form-item>
      </re-col>
    </el-row>
    <el-row justify="center">
      <re-col :value="16">
        <el-form-item label="角色标识" prop="roleCode">
          <el-input
            v-model="newFormInline.roleCode"
            clearable
            placeholder="请输入角色标识"
          />
        </el-form-item>
      </re-col>
    </el-row>
    <el-row justify="center">
      <re-col :value="16">
        <el-form-item label="关联菜单">
          <div v-loading="treeLoading" class="tree-box scrollBar">
            <el-tree
              ref="treeRef"
              :data="treeData"
              show-checkbox
              node-key="id"
              default-expand-all
              check-on-click-node
              check-strictly
              :expand-on-click-node="false"
              :props="defaultProps"
            />
          </div>
        </el-form-item>
      </re-col>
    </el-row>
  </el-form>
</template>
<style scoped>
.tree-box {
  width: 100%;
  height: 380px;
  overflow: auto;
  margin-top: 10px;
  padding: 5px 10px;
  border: 1px solid #ededed;
}
</style>
